﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SQLite.Net;
using SQLite.Net.Attributes;
using SQLite.Net.Platform.WinRT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MyselfPage : Page
    {
        public delegate void PageChnage(MyBangumi my);
        public event PageChnage PageChnageEvent;
        public MyselfPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            //await Task.Delay(1000);
            GetMyBangumi();
            pr_Load.Visibility = Visibility.Visible;
            btn_Refresh.IsEnabled = false;
            if (list_Home.Items.Count != 0)
            {
                foreach (MyBangumi item in list_Home.Items)
                {
                    switch (item.Type)
                    {
                        case 1:
                            await GetBiliNew(item);
                            break;
                        case 2:
                            await GetDiliNew(item);
                            break;
                        case 3:
                            await GetFCNew(item);
                            break;
                        default:
                            break;
                    }
                }
            }
            btn_Refresh.IsEnabled = true;
            GetMyBangumi();
            pr_Load.Visibility = Visibility.Collapsed;
        }
        private  void GetMyBangumi()
        {
            List<MyBangumi> my = new List<MyBangumi>();
            using (var conn = AppDatabase.GetDbConnection())
            {
                var dbPerson = conn.Table<MyBangumi>();
                foreach (MyBangumi item in dbPerson)
                {
                    my.Add(item);
                }
                list_Home.ItemsSource = my;
               // pr_Load.Visibility = Visibility.Collapsed;
            }
            if (my.Count==0)
            {
                txt_Non.Visibility = Visibility.Visible;
            }
            else
            {
                txt_Non.Visibility = Visibility.Collapsed;
            }
        }

        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            pr_Load.Visibility = Visibility.Visible;
            btn_Refresh.IsEnabled = false;
            if (list_Home.Items.Count!=0)
            {
                foreach (MyBangumi item in list_Home.Items)
                {
                    switch (item.Type)
                    {
                        case 1:
                            await GetBiliNew(item);
                            break;
                        case 2:
                            await GetDiliNew(item);
                            break;
                        case 3:
                            await GetFCNew(item);
                            break;
                        default:
                            break;
                    }
                }
            }
            btn_Refresh.IsEnabled = true;
            GetMyBangumi();
            pr_Load.Visibility = Visibility.Collapsed;
        }

        private void list_Home_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent((e.ClickedItem as MyBangumi));
        }

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int i = Convert.ToInt32(this.ActualWidth / 100);
            ViewBox_num.Width = this.ActualWidth / i - 11;
        }

        private void select_Checked(object sender, RoutedEventArgs e)
        {

            list_Home.SelectionMode = ListViewSelectionMode.Multiple;
            list_Home.IsItemClickEnabled = false;
        }

        private void select_Unchecked(object sender, RoutedEventArgs e)
        {
            list_Home.SelectionMode = ListViewSelectionMode.None;
            list_Home.IsItemClickEnabled = true;
        }

        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            foreach (MyBangumi item in list_Home.SelectedItems)
            {
                using (var conn = AppDatabase.GetDbConnection())
                {
                    conn.Execute("DELETE FROM MyBangumi WHERE Info=?",item.Info);
                }
            }
            GetMyBangumi();
        }
        WebClientClass wc;
        private async Task GetBiliNew(MyBangumi par)
        {
            try
            {
               // pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                string uri = "";
                uri = string.Format("http://bangumi.bilibili.com/api/season?_device=wp&access_key={2}&_ulv=10000&build=411005&platform=android&appkey=422fd9d7289a1dd9&ts={0}000&type=bangumi&season_id={1}", BiliApiHelper.GetTimeSpen, par.Info, BiliApiHelper.access_key);
                uri += "&sign=" + BiliApiHelper.GetSign(uri);
                string result = await wc.GetResults(new Uri(uri));
                BangumiInfoModel model = new BangumiInfoModel();
                if ((int)JObject.Parse(result)["code"] == 0)
                {
                    model = JsonConvert.DeserializeObject<BangumiInfoModel>(JObject.Parse(result)["result"].ToString());
                    //grid_Info.DataContext = model;

                    BangumiInfoModel m = JsonConvert.DeserializeObject<BangumiInfoModel>(model.user_season.ToString());

                    List<BangumiInfoModel> list = JsonConvert.DeserializeObject<List<BangumiInfoModel>>(model.episodes.ToString());
                    //list_E.ItemsSource = list;
                    if (list.Count != 0)
                    {
                        par.New = list[0].index;
                        using (var conn = AppDatabase.GetDbConnection())
                        {
                            conn.Execute("UPDATE MyBangumi SET New=? WHERE Info=?;", par.New, par.Info);
                        }
                    }
                   

                }
            }
            catch (Exception)
            {
                //messShow.Show("发生错误\r\n" + ex.Message, 3000);
            }
            finally
            {
                //pr_Load.Visibility = Visibility.Collapsed;

            }
        }
        private async Task GetDiliNew(MyBangumi par)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();

                string results = await wc.GetResultsUTF8Encode(new Uri(par.Info));
                DModel info = new DModel();

                MatchCollection mc = Regex.Matches(results, @"<li><a href=""(.*?)"" target=""_self""><em><span>(.*?)</span>(.*?)</em></a></li>", RegexOptions.Multiline);
                List<DModel> listModel = new List<DModel>();
                foreach (Match item in mc)
                {
                    listModel.Add(new DModel()
                    {
                        url = item.Groups[1].Value,
                        num = item.Groups[2].Value,
                        desc = item.Groups[3].Value
                    });
                }
                if (listModel.Count != 0)
                {
                    par.New = listModel[listModel.Count - 1].num;
                    using (var conn = AppDatabase.GetDbConnection())
                    {
                        conn.Execute("UPDATE MyBangumi SET New=? WHERE Info=?;", par.New, par.Info);
                    }
                }
               
            }
            catch (Exception)
            {
                
            }
            finally
            {
              
            }
        }
        private async Task GetFCNew(MyBangumi par)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();

                string results = await wc.GetResultsGBKEncode(new Uri(par.Info));
                DModel info = new DModel();

                MatchCollection mc = Regex.Matches(results, @"<li><a title='(.*?)' href='(.*?)' target=.*?</li>", RegexOptions.Singleline);
                List<FCInfoModel> listModel = new List<FCInfoModel>();
                foreach (Match item in mc)
                {
                    listModel.Add(new FCInfoModel()
                    {
                        url = "http://m.fengchedm.com" + item.Groups[2].Value,
                        num = item.Groups[1].Value,
                    });
                }
                if (listModel.Count != 0)
                {
                    par.New = listModel[0].num;
                    using (var conn = AppDatabase.GetDbConnection())
                    {
                        conn.Execute("UPDATE MyBangumi SET New=? WHERE Info=?;", par.New, par.Info);
                    }
                }
                //list_Video.ItemsSource = listModel;
            }
            catch (Exception)
            {
               // messShow.Show("读取失败", 3000);
            }
            finally
            {
                //pr_Load.Visibility = Visibility.Collapsed;
            }
        }

    }

    


    public class MyBangumi
    {
        public string New { get; set; }
        public string Img { get; set; }
        public int Type { get; set; }//1为Bili,2为Dili，3为FC
        public string Title { get; set; }
        [PrimaryKey]// 主键。
        public string Info { get; set; }

    }

    public static class AppDatabase
    {
        /// <summary>
        /// 数据库文件所在路径，这里使用 LocalFolder，数据库文件名叫 test.db。
        /// </summary>
        public readonly static string DbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "my.db");

        public static SQLiteConnection GetDbConnection()
        {
            // 连接数据库，如果数据库文件不存在则创建一个空数据库。
            var conn = new SQLiteConnection(new SQLitePlatformWinRT(), DbPath);
            // 创建 Person 模型对应的表，如果已存在，则忽略该操作。
            conn.CreateTable<MyBangumi>();
            return conn;
        }
    }

}
